package com.qinglei.recoup.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.common.domain.Tree;
import com.qinglei.recoup.common.tenant.TenantContextHolder;
import com.qinglei.recoup.system.dao.NurseBedMapper;
import com.qinglei.recoup.system.domain.Bed;
import com.qinglei.recoup.system.domain.BedTreeAttachBO;
import com.qinglei.recoup.system.domain.NurseBed;
import com.qinglei.recoup.system.domain.User;
import com.qinglei.recoup.system.enums.RoleEnum;
import com.qinglei.recoup.system.pojo.BedVO;
import com.qinglei.recoup.system.pojo.NurseDetailVO;
import com.qinglei.recoup.system.pojo.NurseRelateBedParam;
import com.qinglei.recoup.system.pojo.PageParam;
import com.qinglei.recoup.system.pojo.PageVO;
import com.qinglei.recoup.system.pojo.UserSearchParam;
import com.qinglei.recoup.system.service.BedService;
import com.qinglei.recoup.system.service.NurseBedService;
import com.qinglei.recoup.system.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author syp
 */
@Service
public class NurseBedServiceImpl extends ServiceImpl<NurseBedMapper, NurseBed> implements NurseBedService {

    @Resource
    private UserService userService;

    @Resource
    private BedService bedService;

    @Override
    public PageVO<NurseDetailVO> getPageList(UserSearchParam pageParam) {
        pageParam.setSortField("u.create_time");
        pageParam.setSortOrder("descend");

        User userQuery = new User();
        userQuery.setRoleId(String.valueOf(RoleEnum.NURSE.getCode()));
        userQuery.setTenantId(TenantContextHolder.getTenantId());
        userQuery.setName(pageParam.getName());
        IPage<User> userDetail = userService.findUserDetail(userQuery, pageParam);
        PageVO<NurseDetailVO> pageVO = new PageVO<>();
        if (userDetail != null && userDetail.getTotal() > 0) {
            List<NurseDetailVO> list = userDetail.getRecords().stream().map(user -> {
                List<BedVO> bedVOS = this.baseMapper.selectBedListByNurse(user.getId());
                NurseDetailVO nurseDetailVO = new NurseDetailVO();
                nurseDetailVO.setUserId(user.getId());
                nurseDetailVO.setName(user.getName());
                nurseDetailVO.setMobile(user.getMobile());
                nurseDetailVO.setRoleId(user.getRoleId());
                nurseDetailVO.setRoleName(user.getRoleName());
                nurseDetailVO.setPassword("");
                nurseDetailVO.setBeds(bedVOS);
                return nurseDetailVO;
            }).collect(Collectors.toList());
            pageVO.setTotal(userDetail.getTotal());
            pageVO.setRows(list);
        }
        return pageVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonRes relateBeds(NurseRelateBedParam param) {
        if (CollectionUtils.isNotEmpty(param.getDelBedIds())) {
            LambdaQueryWrapper<NurseBed> queryWrapper = Wrappers.<NurseBed>lambdaQuery()
                    .eq(NurseBed::getUserId, param.getUserId())
                    .in(NurseBed::getBedId, param.getDelBedIds());
            this.remove(queryWrapper);
        }
        if (CollectionUtils.isNotEmpty(param.getAddBedIds())) {
            List<Integer> addBedIds = param.getAddBedIds();
            for (Integer abi : addBedIds) {
                List<NurseBed> nurseBeds = baseMapper.selectList(Wrappers.<NurseBed>lambdaQuery().eq(NurseBed::getUserId, param.getUserId()).eq(NurseBed::getBedId, abi));
                if (nurseBeds.size() > 0) {
                    return CommonRes.failed("该护工已绑定此床位");
                }
            }
            List<NurseBed> nurseBedList = param.getAddBedIds().stream().map(bedId -> {
                NurseBed nurseBed = new NurseBed();
                nurseBed.setBedId(bedId);
                nurseBed.setUserId(param.getUserId());
                return nurseBed;
            }).collect(Collectors.toList());
            this.saveBatch(nurseBedList);
        }

        return CommonRes.ok();
    }

    /**
     * 根据床位ID查询护工ID集合
     *
     * @param bedId
     * @return
     */
    @Override
    public Set<Long> getNurseIdsByBed(Integer bedId) {
        List<Long> userIds = this.baseMapper.selectNurseIdsByBed(bedId);
        return new HashSet<>(userIds);
    }

    @Override
    public Tree<Bed> getBedTree4Nurse(Long userId) {
        List<NurseBed> nurseBeds = this.baseMapper.selectList(Wrappers.<NurseBed>lambdaQuery()
                .select(NurseBed::getBedId)
                .eq(NurseBed::getUserId, userId));
//                .eq(userId != null, NurseBed::getUserId, userId));
        Set<Integer> bedIds = nurseBeds.stream().map(NurseBed::getBedId).collect(Collectors.toSet());
        BedTreeAttachBO disabledData = new BedTreeAttachBO();
        disabledData.setBedIds(bedIds);
        Tree<Bed> bedTree = bedService.getBedTree(disabledData);
        return bedTree;
    }
}
